<?php

function getanswer($ask, $aid, $tipid) {
    global $_FANWE;

    if($aid) {
        $sql = 'SELECT * FROM '.FDB::table('wogu_robot_answers').' WHERE id='.$aid;
        $answerinfo = FDB::fetchFirst($sql);
        $suggest = $tipid == 0 ? $answerinfo['suggest1'] : $answerinfo['suggest2'];
        return $suggest;
    }

    require_once FANWE_ROOT.'./core/include/phpanalysis2.0/phpanalysis.class.php';
    PhpAnalysis::$loadInit = false;
    $pa = new PhpAnalysis('utf-8', 'utf-8', false);
    $pa->LoadDict();
    $pa->SetSource($ask);
    $pa->differMax = true;
    $pa->unitWord = true;
    $pa->StartAnalysis(true);
    $keywordstr = $pa->GetFinallyResult(',', false);
    $keywordarr = explode(',', trim($keywordstr, ','));
    if(in_array('如何', $keywordarr) && in_array('自制', $keywordarr) && in_array('火锅', $keywordarr)) {
        $catids = array(158, 159, 160, 161, 162);
        $completedids = empty($_FANWE['user']['robot_completed']) ? array() : explode(',', $_FANWE['user']['robot_completed']);
        $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id IN('.implode(',', $catids).')';
        $cates = FDB::fetchAll($sql);
        $answer = '想自制火锅？看看下面这些准备好没<br>';
        foreach($cates as $v) {
            $iscompleted = in_array($v['cate_id'], $completedids);
            $answer .= '<p><input type="checkbox" value="'.$v['cate_id'].'"'.($iscompleted ? ' disabled="true" checked="true"' : 'onclick="docomplete('.$v['cate_id'].', this)"').' />'.$v['cate_name'].'</p>';
        }
    } else {
        $sql = 'SELECT * FROM '.FDB::table('wogu_robot_keyword').' WHERE keyword IN(\''.implode("','", $keywordarr).'\')';
        $res = FDB::query($sql);
        while($v = FDB::fetch($res)) {
            $keywordvals[] = $v['keyword'];
            $keywords[] = $v;
        }
        $keywordvals = array_unique($keywordvals);
        $arr = array();
        $len = count($keywordvals);
        if($len <= 2) {
            foreach($keywords as $v) {
                $arr[$v['keyword']][] = $v['aid'];

                $sql = 'SELECT * FROM '.FDB::table('wogu_robot_keyword').' WHERE aid='.$v['aid'];
                $res = FDB::query($sql);
                $keywordvals2 = array();
                $arrtmp = array();
                while($v1 = FDB::fetch($res)) {
                    $keywordvals2[] = $v1['keyword'];
                    $arrtmp[$v1['keyword']][] = $v1['aid'];
                }
                $diff = array_diff($keywordvals, $keywordvals2);
                if(count($keywordvals2) == $len && empty($diff)) {
                    $arr = $arrtmp;
                    break;
                }
            }

        } else {
            foreach($keywords as $v) {
                $arr[$v['keyword']][] = $v['aid'];
            }
        }

        if(count($arr) == 1 && isset($arr['火锅'])) {
            $answer = '请到';
            $sql = 'SELECT * FROM '.FDB::table('wogu_list_session').' WHERE uid='.$_FANWE['uid'];
            $arr = FDB::fetchAll($sql);
            $catids = array();
            foreach($arr as $v) {
                $catids[] = $v['cate_id'];
            }
            if(!empty($catids)) {
                $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE parent_id!=0 AND listshow=0 AND cate_id NOT IN('.implode(',', $catids).')';
                $cates = FDB::fetchAll($sql);
                $catnames = array();
                foreach($cates as $v) {
                    $catnames[] = $v['cate_name'];
                }
                $answer .= implode(',', $catnames).'了解详情';
            }

            $catids = array(75, 76, 77);
            $pids = empty($_COOKIE['pids']) ? array() : explode(',', $_COOKIE['pids']);
            if(!empty($pids)) {
                $sql = 'SELECT * FROM '.FDB::table('wogu_product').' WHERE id IN('.implode(',', $pids).')';
                $arr = FDB::fetchAll($sql);
                $hadcatids = array();
                foreach($arr as $v) {
                    $hadcatids[] = $v['cate_id'];
                }
                $hadcatids = array_unique($hadcatids);
                $catids = array_diff($catids, $hadcatids);
            }
            if(!empty($catids)) {
                $sql = 'SELECT * FROM '.FDB::table('goods_category').' WHERE cate_id IN('.implode(',', $catids).')';
                $cates = FDB::fetchAll($sql);
                $pcatnames = array();
                foreach($cates as $v) {
                    $pcatnames[] = $v['cate_name'];
                }

                $answer .= (empty($catnames) ? '' : '，并去').implode(',', $pcatnames).'享受优惠。';
            }
        } else {
            if(count($arr) == 1) {
                $ins = current($arr);
            } else {
                $keys = array_keys($arr);
                for($i = count($arr); $i > 1; $i--) {
                    $data = getCombinationToString($keys, $i);
                    foreach($data as $s) {
                        $indexes = explode(',', $s);
                        $newarr = array();
                        foreach($indexes as $index)
                            $newarr[] = $arr[$index];

                        $ins = call_user_func_array('array_intersect', $newarr);
                        if(!empty($ins)) {
                            break 2;
                        }
                    }
                }
            }

            if(!empty($ins)) {
                session_start();
                $ins = array_values($ins);
                $key = md5($ask);
                $aidkey = (isset($_SESSION[$key]) && $_SESSION[$key] <= (count($ins) -1)) ? $_SESSION[$key] : 0;
                $aid = $ins[$aidkey];
                $sql = 'SELECT * FROM '.FDB::table('wogu_robot_answers').' WHERE id='.$aid;
                $_SESSION[$key] = $aidkey+1;
                $answerinfo = FDB::fetchFirst($sql);
                $answer = $answerinfo['answer'];
                if(!empty($answerinfo['tip1'])) {
                    $answer .= '<p><a href="javascript:suggest('.$answerinfo['id'].',0);">'.$answerinfo['tip1'].'</a></p><p><a href="javascript:suggest('.$answerinfo['id'].',1);">'.$answerinfo['tip2'].'</a></p>';
                }
            } else {
                $sql = 'SELECT id,robot_keyword,name FROM '.FDB::table('wogu_user_shop').' WHERE robot_keyword!=\'\'';
                $sinfos = FDB::fetchAll($sql);
                $find = false;
                if(!empty($sinfos)) {
                    foreach($sinfos as $sinfo) {
                        if(false !== strpos($ask, $sinfo['robot_keyword'])) {
                            $answer = '你是在找商家<a href="/shopinfo.php?action=show&id='.$sinfo['id'].'" target="_blank">'.$sinfo['name'].'</a>吗？';
                            $find = true;
                            break;
                        }
                    }
                }

                if(!$find) {
                    $artitle = strstr($ask, '案例');
                    if(false !== $artitle) {
                        $artitle = str_replace(array('案例',' ','+'), '', $artitle);
                        $sql = 'SELECT id,title FROM '.FDB::table('article').' WHERE title LIKE \'%'.$artitle.'%\'';
                        $article = FDB::fetchFirst($sql);
                        if(!empty($article)) {
                            $answer = '你是在找案例<a href="/article.php?action=show&id='.$article['id'].'" target="_blank">'.$article['title'].'</a>吗？';
                        }
                    }
                }

                if(empty($answer))
                    $answer = '听不懂你说什么...';
            }
        }
    }

    return $answer;
}

function getCombinationToString($arr,$m)
{
    $result = array();
    if ($m ==1)
    {
        return $arr;
    }

    if ($m == count($arr))
    {
        $result[] = implode(',' , $arr);
        return $result;
    }

    $temp_firstelement = $arr[0];
    unset($arr[0]);
    $arr = array_values($arr);
    $temp_list1 = getCombinationToString($arr, ($m-1));

    foreach ($temp_list1 as $s)
    {
        $s = $temp_firstelement.','.$s;
        $result[] = $s;
    }
    unset($temp_list1);

    $temp_list2 = getCombinationToString($arr, $m);
    foreach ($temp_list2 as $s)
    {
        $result[] = $s;
    }
    unset($temp_list2);

    return $result;
}

function dopay($mix, $paystep, $isorder = false) {
    global $_FANWE;

    if(!$isorder) {
        $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE id='.$mix;
        $item = FDB::fetchFirst($sql);
        $sql = 'SELECT * FROM '.FDB::table('wogu_order').' WHERE id='.$item['orderid'];
        $order = FDB::fetchFirst($sql);
    } else {
        $order = $mix;
        $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid='.$order['userid'];
        $userinfo = FDB::fetchFirst($sql);
        $_FANWE['uid'] = $userinfo['uid'];
        $_FANWE['user']['user_name'] = $userinfo['user_name'];
    }

    if($paystep == 1) {
        $money = $order['total_fee'] * 0.3;
        $msg = "买家{$_FANWE['user']['user_name']}向您支付30%的定金（订单号:{$order['orderid']}），共计{$money}元！";
        $msg1 = "购买案例《{$order['ordername']}》支出{$money}元(30%)";
    } elseif($paystep == 2) {
        $money = $order['total_fee'] * 0.8;
        $msg = "买家{$_FANWE['user']['user_name']}向您支付80%的费用（订单号:{$order['orderid']}），共计{$money}元！";
        $msg1 = "购买案例《{$order['ordername']}》支出{$money}元(50%)";
        $sql = 'UPDATE '.FDB::table('user').' SET rmb=rmb+'.$money.' WHERE uid='.$order['shopid'];
        FDB::query($sql);
    } elseif($paystep == 3) {
        $msg = "买家{$_FANWE['user']['user_name']}已支付全部费用（订单号:{$order['orderid']}），共计{$order['total_fee']}元！";
        $msg1 = "购买案例《{$order['ordername']}》支出{$money}元(20%)";
        $money = $order['total_fee'] * 0.2;
        $sql = 'UPDATE '.FDB::table('user').' SET rmb=rmb+'.$money.' WHERE uid='.$order['shopid'];
        FDB::query($sql);

        // 优惠券
        $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid='.$_FANWE['uid'];
        $userinfo = FDB::fetchFirst($sql);
        if($userinfo['coupon_status'] == 1) {
            $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE uid='.$order['shopid'];
            $shopinfo = FDB::fetchFirst($sql);
            if($shopinfo['stype'] == 1) {
                $backmoney = $order['total_fee'] > 1000 ? 1000 : $order['total_fee'];
            } else {
                $tmp = $order['total_fee'] * 0.1;
                $backmoney = $tmp > 1000 ? 1000 : $tmp;
            }

            $sql = 'UPDATE '.FDB::table('user').' SET rmb=rmb+'.$backmoney.',coupon_status=2 WHERE uid='.$_FANWE['uid'];
            FDB::query($sql);

            $msg2 = "订单{$order['orderid']}已完成交易，使用1张优惠券，共返现{$backmoney}元！";
            FDB::query("INSERT INTO ".FDB::table("sys_notice")." (uid, title, content, create_time) VALUES({$_FANWE['uid']},'优惠券返现通知','{$msg2}','".time()."')");
            FS('User')->setUserTips($_FANWE['uid'], 6);

            $sql = "INSERT INTO ".FDB::table('wogu_bill')." (uid,out_in,msg,dateline) VALUES('{$_FANWE['uid']}','1','{$msg2}','".time()."')";
            FDB::query($sql);
        }

    }

    // log
    $sql = "INSERT INTO ".FDB::table('wogu_bill')." (uid,out_in,msg,dateline) VALUES('{$_FANWE['uid']}','0','{$msg1}','".time()."')";
    FDB::query($sql);
    $sql = "INSERT INTO ".FDB::table('wogu_bill')." (uid,out_in,msg,dateline) VALUES('{$order['shopid']}','1','{$msg}','".time()."')";
    FDB::query($sql);

    FDB::query("INSERT INTO ".FDB::table("sys_notice")." (uid, title, content, create_time) VALUES({$order['shopid']},'付款通知','{$msg}','".time()."')");
    FS('User')->setUserTips($order['shopid'], 6);
}

function create_mob_img($img) {
    $dst_width = 240;
    $dst_height = 180;

    if(empty($img)) {
        return;
    }

    if(0 === strpos($img, 'http://')) {
        $mobimg = './public/imgcache/' . substr($img, 7);
        $dir = dirname($mobimg);
        if(!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
    } else {
        $img = $img[0] == '/' ? ('.'.$img) : $img;
        $mobimg = $img . '.mob.jpg';
    }

    if(is_file($mobimg)) {
        return $mobimg;
    }

    list($width, $height) = getimagesize($img);
    $im_src = imagecreatefromjpeg($img);
    if(!$width || !$height || !$im_src) {
        return;
    }

    $im_dst = imagecreatetruecolor($dst_width, $dst_height);
    if($width <= $dst_width) {
      $height = $height >= $dst_height ? $dst_height : $height;
    } elseif($height <= $dst_height) {
      $width = $width >= $dst_width ? $dst_width : $width;
    } else {
      $height1 = $width / $dst_width * $dst_height;
      $height = $height >= $height1 ? $height1 : $height;
    }

    //header("CONTENT-TYPE:IMAGE/JPEG");
    imagecopyresampled($im_dst, $im_src, 0, 0, 0, 0, $dst_width, $dst_height, $width, $height);
    imagejpeg($im_dst, $mobimg, 100);
    //imagejpeg($im_dst);
    imagedestroy($im_src);
    imagedestroy($im_dst);
    //exit;
    return $mobimg;
}

function sendMail($user, $pass, $to, $title, $content) {
    global $_FANWE;

    require_once FANWE_ROOT.'./core/function/PHPMailer/PHPMailerAutoload.php';

    //实例化PHPMailer核心类
    $mail = new PHPMailer();

    //是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
    $mail->SMTPDebug = 0;

    //使用smtp鉴权方式发送邮件
    $mail->isSMTP();

    //smtp需要鉴权 这个必须是true
    $mail->SMTPAuth=true;

    //链接qq域名邮箱的服务器地址
    $mail->Host = 'smtp.qq.com';

    //设置使用ssl加密方式登录鉴权
    $mail->SMTPSecure = 'ssl';

    //设置ssl连接smtp服务器的远程服务器端口号，以前的默认是25，但是现在新的好像已经不可用了 可选465或587
    $mail->Port = 465;

    //设置smtp的helo消息头 这个可有可无 内容任意
    // $mail->Helo = 'Hello smtp.qq.com Server';

    //设置发件人的主机域 可有可无 默认为localhost 内容任意，建议使用你的域名
    $mail->Hostname = $_FANWE['site_url'];

    //设置发送的邮件的编码 可选GB2312 我喜欢utf-8 据说utf8在某些客户端收信下会乱码
    $mail->CharSet = 'UTF-8';

    //设置发件人姓名（昵称） 任意内容，显示在收件人邮件的发件人邮箱地址前的发件人姓名
    $mail->FromName = $_FANWE['setting']['site_name'];

    //smtp登录的账号 这里填入字符串格式的qq号即可
    $mail->Username = $user;

    //smtp登录的密码 使用生成的授权码（就刚才叫你保存的最新的授权码）
    $mail->Password = $pass;

    //设置发件人邮箱地址 这里填入上述提到的“发件人邮箱”
    $mail->From = $user;

    //邮件正文是否为html编码 注意此处是一个方法 不再是属性 true或false
    $mail->isHTML(true);

    //设置收件人邮箱地址 该方法有两个参数 第一个参数为收件人邮箱地址 第二参数为给该地址设置的昵称 不同的邮箱系统会自动进行处理变动 这里第二个参数的意义不大
    $mail->addAddress($to);

    //添加多个收件人 则多次调用方法即可
    // $mail->addAddress('xxx@163.com','lsgo在线通知');

    //添加该邮件的主题
    $mail->Subject = $title;

    //添加邮件正文 上方将isHTML设置成了true，则可以是完整的html字符串 如：使用file_get_contents函数读取本地的html文件
    $mail->Body = $content;

    //为该邮件添加附件 该方法也有两个参数 第一个参数为附件存放的目录（相对目录、或绝对目录均可） 第二参数为在邮件附件中该附件的名称
    // $mail->addAttachment('./d.jpg','mm.jpg');
    //同样该方法可以多次调用 上传多个附件
    // $mail->addAttachment('./Jlib-1.1.0.js','Jlib.js');

    $status = $mail->send();

    //简单的判断与提示信息
    if($status) {
        return true;
    }else{
        return false;
    }
}

// admin@huoguoge.com fsyryrqccttxbhge